#!/usr/bin/env python
#
#       analyze.py
#
#       Copyright 2008 karthikeyan S.<kaarthikeyapreyan@gmail.com>
#
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

from types import ClassType,TypeType,FunctionType

import grouped
import pytestgenerator

def analyzeclass(module):
    """
    Returns the class members of the module
    """
    mod_status=pytestgenerator.TestGenerator().importcheck(module)
    if mod_status[0]:
        return grouped._gathercomponents(mod_status[1],'class')
    else:
        return mod_status[1]

def analyzefunction(module):
    """
    Returns the function members of the module
    """
    mod_status=pytestgenerator.TestGenerator().importcheck(module)
    if mod_status[0]:
        return grouped._gathercomponents(mod_status[1],'function')
    else:
        return mod_status[1]

def analyzemethod(module):
    """
    Return the methods along with the parent
    """
    methlist=[]
    mod_status=pytestgenerator.TestGenerator().importcheck(module)
    if mod_status[0]:
        for entity in grouped._gathercomponents(mod_status[1],'class'):
            methlist.extend(grouped._getmethods(mod_status[1],entity))
        return methlist
    else:
        return mod_status[1]

def getclassmethods(module,class_):
    """
    Returns all the methods of the class
    """
    mod_status=pytestgenerator.TestGenerator().importcheck(module)
    if mod_status[0]:
        return grouped._getmethods(mod_status[1],class_,opt='raw')
    else:
        return mod_status[1]

def analyzemodule(module):
    """
    Return the Class,Method,Function
    in the module
    """
    mod_directory=[]
    mod_status=pytestgenerator.TestGenerator().importcheck(module)
    if mod_status[0]:
        mod_attr=mod_status[1]
        for name in dir(mod_attr):
            member = getattr(mod_attr, name)
            if type(member) in (ClassType,TypeType):
                mod_directory.append([name,'class'])
            elif type(member) == FunctionType:
                mod_directory.append([name,'function'])

        temp_meth=analyzemethod(module)
        map(lambda idx: idx.insert(1,'method'),temp_meth)
        map(lambda meth: mod_directory.append(meth),temp_meth)

    return mod_directory
